import { defineStore } from 'pinia';
import { storage } from '@/utils/storage';
import { loginApi, getUserInfoApi } from '@/api/public';
import { ref } from 'vue';

export const useUserStore = defineStore('user', () => {
	
	const userInfo = ref({})
	
	const login = async () => {
		return new Promise((resolve, reject) => {
		    uni.login({
				provider: 'weixin',
				success: async ({ code }) => {
					try {
						const res = await loginApi({ code });
						storage().set('ACCESS_TOKEN', res.data.accessToken);
						getUserInfo();
						resolve(res);
					} catch (err) {
						reject(err);
					}
				},
				fail: (err) => {
				reject(err);
				}
		    });
		});
	}
	
	const getUserInfo = async () => {
		try {
			const res = await getUserInfoApi()
			userInfo.value = res.data
		} catch {
		}
	}
	
	const clearUserInfo = () => {
		userInfo.value = {}
		storage().remove('ACCESS_TOKEN')
	}
	
    return {
		userInfo,
		login,
		getUserInfo,
		clearUserInfo
    }
})